const socket = require('socket.io');
const config = require('./config.json');
const app = socket('3000');
const mydb = require('./unitily/db');

mydb.connect(config.dbconfig);
// mydb.checkPalyer('100000', (err, db) => {

// });
// mydb.insertPalyer({
//     unique_id: '100000',
//     uid: '12000000',
//     nick_name: '小明',
//     avatar_url: 'baidu.com',
//     house_card_count: 5
// });
// mydb.updatePlayerInfo('100000', {
//     nick_name: '小红',
//     avatar_url: 'sina.com'
// });


app.on('connection', function(socket){
    console.log('a user connected!');
    socket.emit('welcome', 'hello world!')

    // socket.on('login', res => {
    socket.on('notify', res => {
        console.log(`a user login = ${JSON.stringify(res)}`);
        let notifyData = res.data;
        let callbackIndex = res.callbackIndex;
        let msg = res.msg;
        switch (msg) {
            case 'login':
                mydb.checkPalyer(notifyData.uniqueID, (err, data) => {
                    if (err) {
                        console.log(`err = ${ err }`);
                    } else {
                        if (data.length === 0) {
                            // 不存在这个玩家
                            console.log('不存在这个玩家');
                            let uid = '1';
                            for (let i = 0; i < 7; i++) {
                                uid += Math.floor(Math.random() * 10);
                            }
                            notifyData.uid = uid;
                            notifyData.houseCardCount = 5;
                            mydb.insertPalyer({
                                unique_id: notifyData.uniqueID,
                                uid: notifyData.uid,
                                nick_name: notifyData.nickName,
                                avatar_url: notifyData.avatarUrl,
                                house_card_count: notifyData.houseCardCount
                            });
                        } else {
                            // 不存在这个玩家
                            console.log('存在这个玩家');
                            mydb.updatePlayerInfo(notifyData.uniqueID, {
                                nick_name: notifyData.nickName,
                                avatar_url: notifyData.avatarUrl
                            });
                        }
                    }
                });
                break;
        
            default:
                break;
        }

        
    });
});

console.log('listen on 3000');